<?php
class Mycommon extends CI_Model
{
    function __construct ()
    { // call the Model constructor 
        parent::__construct(); // load database class and connect to MySQL
    }
    function getCategoryAsSelect ($selected = -1)
    {
        $this->load->model('MPTtree');
        $this->MPTtree->set_table('categories');
        $lft = 1;
        $node = $this->MPTtree->get_node($lft);
        $str = '';
        $right = array();
        $query = $this->db->query(
        'SELECT ' . $this->MPTtree->id_col . ',' . $this->MPTtree->title_col .
         ', ' . $this->MPTtree->left_col . ', ' . $this->MPTtree->right_col .
         ' FROM ' . $this->MPTtree->tree_table . ' WHERE ' .
         $this->MPTtree->left_col . ' BETWEEN ' . $node[$this->MPTtree->left_col] .
         ' AND ' . $node[$this->MPTtree->right_col] . ' ORDER BY ' .
         $this->MPTtree->left_col . ' ASC');
        $str .= '<SELECT name="s_category">';
        foreach ($query->result_array() as $row) {
            if (count($right) > 0) {
                while ($right[count($right) - 1] <
                 $row[$this->MPTtree->right_col]) {
                    array_pop($right);
                }
            }
            $sel = ($row[$this->MPTtree->id_col] == $selected) ? 'selected="selected"' : '';
//            print_r($sel);
            $str .= '<option value="' . $row[$this->MPTtree->id_col] . '" ' .
             $sel . '>';
         //   $str .= $row[$this->MPTtree->id_col];
            $str .= str_repeat('- ', count($right)) .
             $row[$this->MPTtree->title_col];
            $str .= '</option><br/>';
            $right[] = $row[$this->MPTtree->right_col];
        }
        $str .= '</SELECT>';
        return $str;
    }
    function delete_directory ($dirname)
    {
        if (is_dir($dirname))
            $dir_handle = opendir($dirname);
        if (! $dir_handle)
            return false;
        while ($file = readdir($dir_handle)) {
            if ($file != "." && $file != "..") {
                if (! is_dir($dirname . "/" . $file))
                    unlink($dirname . "/" . $file);
                else
                    $this->delete_directory($dirname . '/' . $file);
            }
        }
        closedir($dir_handle);
        rmdir($dirname);
    }
    function getCategoryAsUL ()
    {
        $this->load->model('MPTtree');
        $this->MPTtree->set_table('categories');
        $lft = 1;
        $tree = $this->MPTtree->tree2array($lft);
        foreach ($tree as $element)
            print_r($element);
        $str = '';
        return $str;
    }
    //    function _buildTree($tree){
    //        $str='<ul>';
    //        foreach ($tree as $element ){
    //            $str=$str.'<li>'.$element['title'].'</li>';
    //            if (array_key_exists('children', $element)) {
    //                $str=$str.$this->_buildTree($tree)
    //}    
    //        }
    //        $str=$str.'</ul>';
    //    }
    /* 
     * http://stackoverflow.com/questions/1310649/getting-a-modified-preorder-tree-traversal-model-nested-set-into-a-ul
     */
    function categoryTreeUL ()
    {
        $query = $this->db->query(
//        'select * from (SELECT node.id,
//    node.title,
//    (COUNT(parent.title) - 1)           AS depth,
//    IF (node.rgt=node.lft+1,true,false) AS isLeaf
//FROM categories                         AS node
//CROSS JOIN categories                   AS parent
//WHERE node.lft BETWEEN parent.lft AND parent.rgt
//GROUP BY node.title
//ORDER BY node.lft) aa
//where depth<=1');
        'SELECT node.id,
        		node.title,
        		(COUNT(parent.title) - 1) AS depth,
        		if (node.rgt=node.lft+1,true,false) as isLeaf
 										FROM categories AS node
									 CROSS JOIN categories AS parent
                                 	WHERE node.lft BETWEEN parent.lft AND parent.rgt 
                                 	
                                 	GROUP BY node.title
                                 	ORDER BY node.lft');
        $tree = array();
        $tree = $query->result_array();
//return $this->_renderTree($tree);
        $res=$this->nestedSetToUL($tree,null,'title','depth');
        $res=substr($res,4);
        
        return  substr($res,0,strlen($res)-5);
        
//        // bootstrap loop
//        $result = "<ul>";
//        $currDepth = 0;
//        $html = "<ul>\n";
//        for ($i = 0; $i < count($tree); $i ++) {
//            $html .= "<li>" . $tree[$i]['title'];
//            if ($tree[$i]['depth'] < $tree[$i + 1]['depth']) {
//                $html .= "\n<ul>\n";
//            } elseif ($tree[$i]['depth'] == $tree[$i + 1]['depth']) {
//                $html .= "</li>\n";
//            } else {
//                $diff = $tree[$i]['depth'] - $tree[$i + 1]['depth'];
//                $html .= str_repeat("</li>\n</ul>\n", $diff) . "</li>\n";
//            }
//        }
//        $result .= "</ul>";
//        $html .= "</ul>\n";
//        return $result;
    }
    function _renderTree ($tree, $currDepth = 0)
    {
        $currNode = array_shift($tree);
        $result = '';
        // Going down?
        if ($currNode['depth'] > $currDepth) {
            // Yes, prepend <ul>
            $result .= '<ul>';
        }
        // Going up?
        if ($currNode['depth'] < $currDepth) {
            // Yes, close n open <ul>
            $result .= str_repeat('</ul>',  $currDepth - $currNode['depth']);
        }
        // Always add the node
        $result .= '<li>' . $currNode['title'] ;//. '</li>';
        // Anything left?
        if (! empty($tree)) {
            // Yes, recurse
            $result .= $this->_renderTree($tree, $currNode['depth']);//.'</li>';
        } else {
            // No, close remaining <ul>
            $result .= '</li>';//str_repeat('</ul>', $currNode['depth'] + 1);
        }
        return $result;
    }
    /*
     * http://www.viper-7.com/snippets/view/37
     */
    function nestedSetToUL($arr, $rootclass = null, $valueKey='value', $levelKey='level')
    {
        $lastlevel = 0;
        $index = 0;
        
        // Create the class attribute for the root element if supplied
        if($rootclass)
            $rootclass = " class=\"{$rootclass}\"";
        
        // Open the unordered list
        $out = "<ul{$rootclass}>";

        // Loop over the array and process each element, ignoring keys
        foreach($arr as $element)
        {
            // If we've gone down one or more levels from the last element
            // Close the <ul> tags until we get to the desired level
            if($element[$levelKey] < $lastlevel)
            {
                $out .= str_repeat('</li></ul>', $lastlevel - $element[$levelKey]);
            }

            // If we're at the same level as the last element,
            // Close the last <li> and open a new one
            if($element[$levelKey] == $lastlevel)
            {
                // Don't close an <li> on the first loop
                // (when there isn't one to close yet)
                if($index) $out .= '</li>';
            }
            
            // If we've gone up one level from the last element
            // Open a <ul> tag for this level
            if($element[$levelKey] == $lastlevel + 1)
            {
                 $out .= '<ul class="sub_menu"><li>';
            }
            // If we've gone up more than one level since the last element,
            // we have no direct parent, so something's gone wrong...
            elseif($element[$levelKey] > $lastlevel)
            {
                throw new Exception("Invalid nested set, no parent for level {$element[$levelKey]}");
            } else {
                // Open the <li> tag for this element
                $out .= '<li>';
            }                

            // Output the element itself
            if ($element['isLeaf'])
                $out .= "<a href=\"".site_url("/home/product/{$element['id']}")."\">{$element[$valueKey]}</a>";
            else 
               $out .= "<a>{$element[$valueKey]}</a>";
            
            // Remember the level of the node we just processed
            $lastlevel = $element[$levelKey];

            // Keep count of what element we're up to
            ++$index;
        }
        
        // Close any open <li> and <ul> tags        
        $out .= str_repeat('</li></ul>', $element[$levelKey] + 1);
        
        return $out;        
    }        
    
    
}
?>